package com.usefullc.crawler.utils;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author: Sampson
 * @date: 10/23/23 4:26 PM
 */
public class ExtractUrlUtils {


    public static String replaceVariables(String url,Map<String,String> variableMap) {
//        // 原始字符串
//        String input = "http://www.baidu.com/${a}/${b}/ab/${c}";
//
//        // 创建一个包含变量名称和值的Map
//        Map<String, String> variableMap = new HashMap();
//        variableMap.put("a","a1");
//        variableMap.put("b","b1");
//        variableMap.put("c","c1");


        // 使用正则表达式匹配${}中的变量名
        Pattern pattern = Pattern.compile("\\$\\{([^}]+)}");
        Matcher matcher = pattern.matcher(url);

        StringBuffer result = new StringBuffer();
        while (matcher.find()) {
            String variableName = matcher.group(1); // 提取变量名
            String replacement = variableMap.get(variableName); // 根据变量名查找替代值
            if (replacement != null) {
                matcher.appendReplacement(result, replacement);
            } else {
                // 如果找不到变量值，可以选择保留原始占位符
                // matcher.appendReplacement(result, "\\${" + variableName + "}");
            }
        }
        matcher.appendTail(result);

        String output = result.toString();
        return output;
//        System.out.println(output); // 输出替换后的字符串
    }
}
